<?php
if (!defined('__COLA_DIR__')) exit;

/**
 * 编辑分类组件
 *
 * @author edikud
 * @package Widget
 * @copyright Copyright (c) 2019 Cola (http://www.mcooo.com)
 * @license GNU General Public License 2.0
 */
class Widget_Metas_Category_Edit extends Widget_Abstract_Metas implements Widget_Interface_Do
{
    /**
     * 入口函数
     *
     * @access public
     * @return void
     */
    public function execute()
    {
        /** 编辑以上权限 */
        $this->user->pass('editor');
		
        /** 更新模式 */
        if (!empty($this->request->mid) && 'delete' != $this->request->do ) {
            $this->select()
                ->where('mid = ?', $this->request->mid)
                ->where('type = ?', 'category')
			    ->limit(1)
			    ->fetchRow(array($this, 'push'));
				
            if (!$this->have()) {
                throw new Widget_Exception(_t('分类不存在'), 404);
            }
        }
    }

    /**
     * 生成表单
     *
     * @access public
     * @param string $action 表单动作
     * @return Form
     */
    public function form()
    {
        /** 构建表格 */
        $form = new Form($this->security->actionUrl('metas-category-edit', false));
		
        /** 分类名称 */
        $name = new Form_Text('name', NULL, NULL, _t('分类名称 *'));
        $form->addInput($name);

        /** 分类缩略名 */
        $alias = new Form_Text('alias', NULL, NULL, _t('分类缩略名'),
        _t('分类缩略名用于创建友好的链接形式, 建议使用字母, 数字, 下划线和横杠.'));
        $form->addInput($alias);

        /** 父级分类 */
        $options = array(0 => _t('不选择'));
        $parents = $this->widget('Widget_Metas_Category_List');
        while ($parents->next()) {
            $options[$parents->mid] = ($parents->level ? '&nbsp;&nbsp;&nbsp;&nbsp;|--' : '') . str_repeat('--', $parents->level) . $parents->name;
        }
        $parent = new Form_Select('parent', $options, $this->request->parent, _t('父级分类'),
        _t('此分类将归档在您选择的父级分类下.'));
        $form->addInput($parent);
		
        /** 分类排序 */
        $order = new Form_Text('order', NULL, 99, _t('分类排序'),
        _t('请输入整数数字.'));
        $form->addInput($order);

        /** 分类描述 */
        $description =  new Form_Textarea('description', NULL, NULL,
        _t('分类描述'), _t('此文字用于描述分类, 在有的主题中它会被显示.'));
        $form->addInput($description);

		/** 分类图标 */
        $pic = new Form_Text('pic', NULL, NULL, _t('分类图标'), '<label class="btn btn-light btn-sm cola-upload"><i class="fe fe-upload mr-2"></i><span>'. _t('上传').'</span><input type="file" accept="image/*" name="file"></label>');
        $form->addInput($pic);
		
        /** 分类动作 */
        $do = new Form_Hidden('do');
        $form->set($do);

        /** 分类主键 */
        $mid = new Form_Hidden('mid');
        $form->addInput($mid);

        /** 提交按钮 */
        $submit = new Form_Submit();
        $form->set($submit);

        if ($this->mid) {
            $name->value($this->name);
            $alias->value($this->alias);
            $parent->value($this->parent);
			$order->value($this->order);
            $description->value($this->description);
            $pic->value($this->pic);
		    $pic->input->set($this->pic ? '<br><img style="margin: 5px 0;" class="cola-pic" src="'.$this->icon .'" />' : '', 'html');
            $do->value('update');
            $mid->value($this->mid);
            $submit->value(_t('编辑分类'));

        } else {
            $do->value('insert');
            $submit->value(_t('增加分类'));
        }

        /** 给表单增加规则 */
        $name->addRule('required', _t('必须填写分类名称'));
        $name->addRule('xssCheck', _t('请不要在分类名称中使用特殊字符'));
        $alias->addRule('xssCheck', _t('请不要在缩略名中使用特殊字符'));
	    $parent->addRule(array($this, 'parentCheck'), _t('父级分类不合法'));

        if ($this->mid) {
			$parent->addRule(array($this, 'lowerCheck'), _t('分类有下级分类，请先删除下级分类'));
			$parent->addRule(array($this, 'contentsNumCheck'), _t('分类中有文章不能修改上级分类，请先删除文章'));
        }
		
		/** 默认上传js (可覆盖或修改) */
        $this->widget('Widget_Scripts')->set("
            (function () {
                $(document).ready(function () {
var jform = $(\"form\");					
jform.on('change', 'input[type=\"file\"]', function(e) {
	var jthis = $(this);
	var jdiv = jthis.parent().parent().parent();
	var jinput = jdiv.find('input[name=\"pic\"]');
	var mid = jform.find('input[name=\"mid\"]').val();//alert(cid);return;
    $.ajax({
		url: '".$this->security->actionUrl('metas-category-edit?do=upload-pic', false)."',
        files: jthis,
        iframe: true,
		data: {mid:mid},
		processData: false,
		dataType: 'text',
		beforeSend: function(s){
			jdiv.find('.cola-upload span').html('正在上传...');
		},
		success: function(s){
		    s = (new Function(\"return \" + s))(); 
		    if(typeof s.code != 'undefined') {
			    if(s.code == 0) {
					if(!$('img', jdiv).length){
						jinput.after('<br><img style=\"margin: 5px 0;\" class=\"cola-pic\" src=\"".$this->options->uploadUrl ."' + s.data.filePath+'?'+Math.random() + '\"/>');
						
					}else{
						$('img', jdiv).attr('src', '".$this->options->uploadUrl ."' + s.data.filePath+'?'+Math.random());
					}
					jinput.val(s.data.filePath);
			    } else {
				   alert(s.msg);
			    }
		    } else {
			    alert(s);
		    }
		},
		complete: function(s){
			jdiv.find('.cola-upload span').html('上传');
		},
    });
});			

});
})();", 'category@upload');
		
		/** 插件接口 */
		//HOOK PLUG_Category_Form($form, $this);
		
        return $form;
    }

	/**  检查上级分类是否合法 */
    public function parentCheck($parent)
    { 
		return (!$this->mid || $this->mid != $parent) && (!$parent || $this->db->select(array('COUNT(*)' => 'num'))
		    ->from('table.metas')
            ->where('mid = ?', $parent)
            ->where('type = ?', 'category')
			->limit(1)
			->fetchObject()
			->num);
	}

	/** 检查分类是否有文章 */
    public function contentsNumCheck($parent)
    { 
        return !($this->parent != $parent && $this->contentsNum);
	}
	
	/** 检查分类是否有下级 */
    public function lowerCheck($parent)
    {
		return !($this->parent != $parent && $this->db->select(array('COUNT(*)' => 'num'))
		    ->from('table.metas')
            ->where('type = ?', 'category')
            ->where('parent = ?', $this->mid)
			->limit(1)
			->fetchObject()
			->num);
	}

    /**
     * 增加分类
     *
     * @access public
     * @return void
     */
    public function insertCategory($values = array())
    {
		/** 插件接口 */
		//HOOK $values | PLUG_Category_Insert($values, $this);		
		
        /** 插入数据 */
        $insertId = $this->insert($values);
		
        if ($insertId > 0) {
			
            /** 同步附件 */
            $this->widget('Widget_Attachs_Edit')->sync('category', $insertId);
		
		    /** 压入数据 */
		    $this->select()
                ->where('mid = ?', $insertId)
			    ->limit(1)
			    ->fetchRow(array($this, 'push'));

			/** 插件接口 */	
		    //HOOK PLUG_Category_Insert_Success($this);
		
		}
		
		return $insertId;
    }

    /**
     * 更新分类
     *
     * @access public
     * @return void
     */
    public function updateCategory($values = array())
    {
		if (!$this->have()) {
		    return ;
		}
		
		/** 插件接口 */
		//HOOK $values | PLUG_Category_Update($values, $this);
		
		$mid = $this->mid;
		
        /** 同步附件 */
        $this->widget('Widget_Attachs_Edit')->sync('category', $mid);
		
        /** 更新数据 */
        $updateRows = $this->update($mid, $values);
		
		/** 压入数据 */
        $this->select()
            ->where('mid = ?', $mid)
            ->limit(1)
		    ->fetchRow(array($this,'push'));

		/** 插件接口 */	
		//HOOK PLUG_Category_Update_Success($this);
		
		return $updateRows;
    }

    /**
     * 删除分类
     *
     * @access public
     * @return void
     */
    public function deleteCategory($mid)
    {
		$deleteRows = false;
		$category = $this->select()
            ->where('mid = ?', $mid)
            ->where('type = ?', 'category')
		    ->limit(1)
		    ->fetchRow(array($this, 'push'));
		
        $pass = $category && !$this->contentsNum && !$this->db->select(array('COUNT(*)' => 'num'))
		    ->from('table.metas')
            ->where('type = ?', 'category')
            ->where('parent = ?', $this->mid)
			->limit(1)
			->fetchObject()
			->num;

        if ($pass) {
			
			/** 插件接口 */
		    //HOOK PLUG_Category_Delete($this);

            /** 删除附件 */
            $this->widget('Widget_Attachs_Edit')->remove('category', $mid);
			
			/** 删除分类 */
		    $deleteRows = $this->delete($mid);

			/** 插件接口 */	
		    //HOOK PLUG_Category_Delete_Success($this);

        }

		return $deleteRows;
    }

    /**
     * 获取菜单标题
     *
     * @return string
     * @throws Widget_Exception
     */
    public function getMenuTitle()
    {
        if ($this->have()) {	
            return _t('编辑: %s', $this->name);
        } else {
            return _t('增加分类');
        }
    }
	
    public function operate()
    {
		$buttons = array();

		$buttons[] = Helper::element('a', _t('全选'), array(
		    'data-selectall'=>NULL,			
			'href'=>'javascript:void(0);'
			)
		);

		$buttons[] = Helper::element('a', _t('删除'), array(
		    'href'=>'javascript:void(0);',
		    'data-action'=>$this->security->actionUrl('metas-category-edit?do=delete', false),
			'data-confirm'=>_t('删除不可恢复，确定删除？'),
			'data-item'=>'mid',
			'style'=>'color:red'
			)
		);
		
		/** 插件接口 */
		//HOOK $buttons[] = | PLUG_Category_Operate($this);

		return $this->widget('Widget_Operate')->render($buttons);
    }
	
    /**
     * 入口函数
     *
     * @access public
     * @return void
     */
    public function action()
    {
        $this->security->protect();
		
        switch ($this->request->do) {
            case 'insert':
			    
				$form = $this->form();
				
		        /** 验证格式 */
                if ($message = $form->validate()) {
                    $this->result->set(key($message), current($message));
                }

                $category = $this->request->from(array_keys($form->getInputs()));
                $category['type'] = 'category';
                $category['order'] = intval($category['order']) >= 0 ? intval($category['order']) : 99;
				
		        $this->insertCategory($category);
			
                /** 提示信息 */
                $this->result->set(0, _t('分类增加成功', $this->name), array('location'=>$this->options->ucenterUrl('categories', false), 'mid'=>$this->mid));
				
            break;
            case 'update':
			
				$form = $this->form();
			
		        /** 验证格式 */
                if ($message = $form->validate()) {
                    $this->result->set(key($message), current($message));
                }

                $category = $this->request->from(array_keys($form->getInputs()));
                $category['order'] = intval($category['order']) >= 0 ? intval($category['order']) : 99;
				
		        $this->updateCategory($category);
			
                /** 提示信息 */
                $this->result->set(0, _t('分类 %s 更新成功', $this->name), array('location'=>$this->options->ucenterUrl('categories', false), 'mid'=>$this->mid));
				
            break;

            case 'delete':
			
                $mids = $this->request->filter('int')->getArray('mid');
                $deleteRows = array();
                foreach ($mids as $mid) {
		            if($this->deleteCategory($mid)){ 
					    $deleteRows[] = $mid;
					}
		        }
			
                /** 设置提示信息 */
                $this->result->set(
				    $deleteRows ? 0 : 1, 
				    $deleteRows ? _t('成功删除 %s 个分类', count($deleteRows)) : _t('没有分类被删除'),
				    $deleteRows
				);

            break;
			
            case 'upload-pic':
			
		        $mid = $this->request->filter('int')->mid;
				
		        /** 删除附件 */
                $this->widget('Widget_Attachs_Edit')->remove('category', $mid);

		        $attach = $this->widget('Widget_Upload')->upload('category', $mid);

                if (!empty($attach)) {

                    /** 更新分类数据 */
                    $mid && $this->update($mid, array('pic'=> $attach['filePath']));
					$this->result->setAjax(true)->set(0, _t('上传成功'), $attach);
                } else {
                    $this->result->setAjax(true)->set(1, _t('上传失败'));
		        }

            break;
			
            case 'delete-pic':

				$mid = $this->request->filter('int')->mid;
				
				$this->widget('Widget_Attachs_Edit')->remove('category', $mid);
				
                /** 更新分类数据 */
                $updateRows = $this->update($mid, array('pic'=> ''));
				
                /** 设置提示信息 */
                $this->result->set($updateRows ? 0 : 1, $updateRows ? _t('删除成功') : _t('删除失败'));

            break;
        }
		$this->result->set(404, _t('请求的资源不存在'));
    }
}
